package com.example.urmsadmin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.urmsadmin.entity.SysRole;
import com.example.urmsadmin.entity.SysUserRole;
import com.example.urmsadmin.service.SysUserRoleService;
import com.example.urmsadmin.service.impl.SysUserRoleServiceImpl;
import com.example.urmsadmin.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户和角色关联表(SysUserRole)表控制层
 *
 * @author makejava
 * @since 2022-07-12 08:43:25
 */
@RestController
@Slf4j
@RequestMapping(value = "/sysUserRole")
public class SysUserRoleController {

    @Autowired
    private SysUserRoleService userRoleService;

    /**
     * @param userId  用户ID
     * @param roleIds 操作角色的id的字符串,以逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@per.hasPermi('system:user:addRole')")
    @GetMapping("/addRoleToUser/{userId}")
    public CommonResult<String> addRoleToUser(@PathVariable("userId") String userId,String roleIds) {
        log.info("执行了===>SysUserRoleController中的addRoleToUser方法");
        userRoleService.removeById(Long.parseLong(userId));
        if(Objects.equals("",roleIds)){
            return new CommonResult<>(200,"操作成功");
        }
        //转换成数组 需要操作的角色的id数组
        String[] ids = roleIds.split(",");
        StringBuilder resultData = new StringBuilder();
        for(String id : ids){
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(Long.parseLong(userId));
            userRole.setRoleId(Long.parseLong(id));
            boolean isSave = userRoleService.save(userRole);
            if(!isSave){
                resultData.append("角色"+id+"分配失败;");
            }
        }
        if("".equals(resultData.toString())){
            return new CommonResult<>(200,"操作成功");
        }
        return new CommonResult<>(233,resultData.toString());
    }

    /**
     * @param userId 用户Id
     * @return
     */
    @GetMapping("/getRoleByUserId")
    public CommonResult<Object> getRoleByUserId(@RequestParam String userId){
        log.info("执行了===>SysUserRoleController中的getRoleByUserId方法");
        //查询条件
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysUserRole> roles = userRoleService.list(wrapper);
        return new CommonResult<>(200, "success", roles);
    }

}

